package com.rosense.client.i;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.dotool.DateTools;
import net.dotool.IoTools;

import com.rosense.client.rpc.RPCBean;
import com.rosense.commons.DateUtils;
import com.rosense.commons.LangUtils;
import com.rosense.commons.NumberUtils;
import com.rosense.server.config.HostCaches;

/**
 * @author 李岩飞
 * @email eliyanfei@126.com	
 * 2018年1月24日 下午2:16:23
 * 
 */
public abstract class IWriteReader {
	public abstract String getName();

	public abstract String getText();

	public abstract void write(String host, RPCBean bean);

	public abstract List<? extends RPCBean> read(String host);

	private File getPath(String host) {
		String ymd = DateTools.formatDate(new Date(), "yyyyMMdd");
		String filePaht = HostCaches.params.get("path") + File.separator + host + File.separator + getName() + File.separator + ymd + ".log";
		File file = new File(filePaht);
		file.getParentFile().mkdirs();
		return file;
	}

	protected void append(String host, String content) {
		PrintWriter out = null;
		try {
			out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(getPath(host), true)));
			out.println(content);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IoTools.closeIos(out);
		}
	}

	protected String readLastLine(String host, String ymd) {
		String filePaht = HostCaches.params.get("path") + File.separator + host + File.separator + getName() + File.separator + ymd + ".log";
		File file = new File(filePaht);
		return readLastLine(file, 50);
	}

	protected String readLastLine(String host) {
		return readLastLine(host, DateTools.formatDate(new Date(), "yyyyMMdd"));
	}
	protected abstract void parserLine(String line, Map<String, String> map);

	public List<Map<String, String>> readAll(String host, String ymd) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		String filePaht = HostCaches.params.get("path") + File.separator + host + File.separator + getName() + File.separator + ymd + ".log";
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(filePaht)));
			String str = null;
			while ((str = br.readLine()) != null) {
				try {
					Map<String, String> map = new HashMap<String, String>();
					list.add(0,map);
					parserLine(str, map);
				} catch (Exception e) {
				}
			}
		} catch (Exception e) {
			System.out.println("文件不存在");
		} finally {
			IoTools.closeIos(br);
		}
		System.out.println(list);
		return list;
	}
	
	protected abstract void parserLineToMap(String line, Map<String, List<RPCBean>> map);

	
	public Map<String,List<RPCBean>> readFile(String filePath){
		Map<String, List<RPCBean>> map = new LinkedHashMap<String, List<RPCBean>>();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
			String str = null;
			while ((str = br.readLine()) != null) {
				parserLineToMap(str,map);
			}
		} catch (Exception e) {
		} finally {
			IoTools.closeIos(br);
		}
		return map;
	}
	
	protected abstract void getAvgInfo(Map<String, List<RPCBean>> mapInfo,Map<String,String> map,double limit);
	
	public Map<String,Map<String, String>> readAlls(String time,String limit) {
		limit = limit.replace("%", "");
		Map<String,Map<String, String>> maps = new HashMap<String, Map<String,String>>();
		List<String> times = getTimes(time);
		for(String host:HostCaches.hostMap.keySet()){
			for(String ymd : times){
				Map<String,String> map = new HashMap<String, String>();
				String filePath = HostCaches.params.get("path") + File.separator + host + File.separator + getName() + File.separator + ymd + ".log";
				Map<String,List<RPCBean>> mapInfo = readFile(filePath);//得到一天的对象
				
				getAvgInfo(mapInfo,map,LangUtils.toDouble(limit));
				if(map.size()!= 0){
					maps.put(host+"_"+ymd, map);
				}
			}
		}
		return maps;
	}
	public Map<String, String> readOnDay(String host,String ymd) {
		Map<String,String> map = new HashMap<String, String>();
		String filePath = HostCaches.params.get("path") + File.separator + host + File.separator + getName() + File.separator + ymd + ".log";
		Map<String,List<RPCBean>> mapInfo = readFile(filePath);//得到一天的对象
		getAvgInfo(mapInfo,map,-1);
		return map;
	}
	public static List<String> getTimes(String time){
		String[] times = time.split("-");
		List<String> list = new ArrayList<String>();
		if(times.length!=2){
			list.add(time);
		}else{
			int time1 = LangUtils.toInt(times[0].trim(),0);
			int time2 =  LangUtils.toInt(times[1].trim(),0);
			while(time1<time2){
				list.add(time1+"");
				Calendar cal = Calendar.getInstance();
				cal.setTime(DateUtils.toDate(time1+"", "yyyyMMdd"));
				cal.add(Calendar.DAY_OF_YEAR, 1);
				time1 = DateUtils.toDateNum(cal.getTime(), "yyyyMMdd");
			}
			
		}
		return list;
	}
	private String readLastLine(File file, int num) {
		if (!file.exists() || file.isDirectory() || !file.canRead()) {
			return null;
		}
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(file, "r");
			long len = raf.length();
			if (len == 0L) {
				return "";
			} else {
				long pos = len - 1;
				int lineNum = 1;
				while (pos > 0) {
					pos--;
					raf.seek(pos);
					if (raf.readByte() == '\n') {
						if (lineNum++ == num) {
							break;
						}
					}
				}
				if (pos == 0) {
					raf.seek(0);
				}
				byte[] bytes = new byte[(int) (len - pos)];
				raf.read(bytes);
				return new String(bytes);
			}
		} catch (Exception e) {
		} finally {
			IoTools.closeIos(raf);
		}
		return null;
	}
}
